<?php
namespace app\index\controller;
use app\service\apiService;
use app\service\cxyunService;
use app\service\orderService;
use think\facade\View;
use think\request;
use think\facade\Db;
use think\facade\Log;
error_reporting(0);
//
class Orderwx extends Wechat{
    public function carquery(){
        $parking_id=request()->get("id");
        $parkinglotinfo=Db::table("parkinglotinfo")->where("id",$parking_id)->find();
        if(empty($parkinglotinfo)){
            return "停车场信息错误";
        }
        View::assign("id",$parking_id);
        return View::fetch();
    }
    public function prepay(){
        $parking_id=request()->get("id");
        $carPlateNo=request()->get("car_number");
        $parkingInfo=Db::table("parkinglotinfo")->where("id",$parking_id)->find();
        if(empty($parkingInfo)){
            return "停车场信息错误";
        }

        $data["parkingId"]=$parkingInfo["cxyun_parking_id"];
        $data["plateNumber"]=$carPlateNo;
        $data["timestamp"]=time()."000";
        $notData=array();
        $cxyunApi=new cxyunService($parkingInfo["cxyun_appkey"]);
        $res=$cxyunApi->commonPost("calculatingTempCost",$data,$notData);
        $result= json_decode($res,true);

        if($result["status"]==0){
            if($result["message"]=="获取临停缴费接口,请检查车场网络!!"){
                return View::fetch("offline");
            }else if($result["message"]=="找不到入场记录!"){
                return View::fetch("nomsg");
            }else if($result["message"]=="不需要缴费!"){
                return View::fetch("nomsg");
            }
            return json(["code"=>500,"msg"=>$result["message"]]);
            return $result["message"];

        }
        $result= json_decode($result["Data"],true);
        $add["parkingId"]=$result["parkingId"];
        $add["parkingNo"]=$parkingInfo["parkingNo"];
        $add["parkingName"]=$parkingInfo["parkingName"];
        $add["plateNumber"]= $data["plateNumber"];
        $add["payFee"]=$result["payFee"];
        $add["totalFee"]=$result["totalFee"];
        $add["upayFee"]=$result["upayFee"];
        $add["orderNo"]=$result["orderNo"];
        $add["stopTime"]=$result["stopTime"];
        $add["inTime"]=$result["inTime"];//$orderinfo.parkingStartTime|strtotime|date="Y-m-d H:i:s"
        $add["discountFee"]=$result["discountFee"];
        $add["user_id"]=session("wechat_openid");;
        $add["createTime"]=date("Y-m-d H:i:s");
        $add["id"]= Db::table("cxyun_query_order_log")->insertGetId($add);
        View::assign("duration",convertTime($add["stopTime"]*60));
        $add["inTime"]=substr($add["inTime"], 0, -4);
        View::assign("order_info",$add);
        View::assign("parkinginfo",$parkingInfo);

        return View::fetch();
    }
    
    public function prepayOrder(){
		//根据ID查询停车场信息
		$id=request()->post("pay_id");
        $order_info=Db::table("cxyun_query_order_log")->where("id",$id)->find();
        if(empty($order_info)){
            return json(['info' => "查询账单失败"]);
        }
        $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$order_info["parkingNo"])->find();
        if(empty($parkinginfo)){
            return json(['info' => "停车场信息错误"]);
        }


        //生成订单
        $data['appid'] = env("APP.WECHAT_ACCOUNT_APPID");//公众账号ID
        $data['mch_id'] =env("APP.WECHAT_MCH_ID");//
        //根据停车场商户ID
        $data['sub_mch_id'] =$parkinginfo["mch_id"];
        $data['nonce_str'] = createNoncestr();//随机字符串
        $data['body'] = $parkinginfo["parkingName"]."-".$order_info["plateNumber"]."-".date('Y-m-d H:i:s');//商品描述
        $data['out_trade_no'] = date('YmdHis').rand(100000,999999);//商户订单号
        $data['total_fee'] = $order_info["upayFee"]*100;//总金额
        //$data['total_fee']=1;
        $data['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
        $data['notify_url'] = $this->getCurrentUrl().'/index/callback/wxnotice';//通知url
        $data['trade_type'] = 'JSAPI';
        $data['openid'] = session("wechat_openid");//用户标识

        $data['sign'] = MakeSign($data,env("APP.WECHAT_KEY"));//签名
        // return json(['info' => $data]);
        //输出xml字符

        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $payInfo = post_curl_data($url,ToXml($data));
        $payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        Log::write($payInfo,"info");
        if($payInfo['return_code'] !== 'SUCCESS'){
            return json(['info' => $payInfo['return_msg']]);
        }if($payInfo['result_code'] !== 'SUCCESS'){
            return json(['info' => $payInfo['err_code_des']]);
        }else{
            unset($order_info["upayFee"]);
            unset($order_info["id"]);
            $info=$order_info;
            $info['query_order_log_id']=$id;
            $info['tradeNo'] =  $payInfo['prepay_id'];
            $info["subject"]=$data['body'];
            $info['outTradeNo'] =$data['out_trade_no'];
            $info["token"]=$data['sub_mch_id'];
            $info["scenes"]=4;
            $info['createTime'] =  date("y-m-d H:i:s");
            $res=Db::table("cxyun_order")->insert($info);
            if($res){
                $jsApiParameters['appId'] = $payInfo['appid'];
                //$jsApiParameters['timeStamp'] = time();
                $jsApiParameters['timeStamp'] = '$jsApiParameters["timeStamp"]';
                $jsApiParameters['nonceStr'] = createNoncestr();
                $jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
                $jsApiParameters['signType'] = 'MD5';
                $jsApiParameters['paySign'] = MakeSigns($jsApiParameters,env("APP.WECHAT_KEY"));
                return json(['jsApiParameters' => json_encode($jsApiParameters)]);
            }else{
                return json(['info' => '订单存储失败']);
            }
        }
	}
    
    public function outpay(){
        $id=request()->get("id");
        //查询出口信息
        $gateinfo=Db::table("cxyun_parking_gate")->where("id",$id)->find();
        if(empty($gateinfo)){
            return "出口信息不存在";
        }
        View::assign("gateinfo",$gateinfo);


        $parkingInfo=Db::table("parkinglotinfo")->where("parkingNo",$gateinfo["parkingNo"])->find();
        View::assign("parkingInfo",$parkingInfo);
        $car_out=Db::table("cxyun_car_out")->where("outLaneCode",$gateinfo['gateId'])->find();
        if(empty($car_out)){
            return View::fetch("nomsg");
        }
        $data["parkingId"]=$parkingInfo["cxyun_parking_id"];
        $data["plateNumber"]=$car_out["plateNumber"];
        $data["timestamp"]=time()."000";
        $notData=array();
        $cxyunApi=new cxyunService($parkingInfo["cxyun_appkey"]);
        $res=$cxyunApi->commonPost("calculatingTempCost",$data,$notData);
        $result= json_decode($res,true);
        if($result["status"]==0){
            if($result["message"]=="获取临停缴费接口,请检查车场网络!!"){
                return View::fetch("offline");
            }else if($result["message"]=="找不到入场记录!"){
                return View::fetch("nomsg");
            }else if($result["message"]=="不需要缴费!"){
                return View::fetch("nomsg");
            }
            return $result["message"];
            //return json(["code"=>500,"msg"=>$result["message"]]);
        }
        $result= json_decode($result["Data"],true);
        $add["parkingId"]=$result["parkingId"];
        $add["parkingNo"]=$parkingInfo["parkingNo"];
        $add["parkingName"]=$parkingInfo["parkingName"];
        $add["plateNumber"]= $data["plateNumber"];
        $add["payFee"]=$result["payFee"];
        $add["totalFee"]=$result["totalFee"];
        $add["upayFee"]=$result["upayFee"];
        $add["orderNo"]=$result["orderNo"];
        $add["stopTime"]=$result["stopTime"];
        $add["inTime"]=$result["inTime"];
        $add["discountFee"]=$result["discountFee"];
        $add["user_id"]=session("wechat_openid");
        $add["createTime"]=date("Y-m-d H:i:s");
        $add["recordId"]=$car_out["recordId"];
        $add["cartypeName"]=$car_out["cartypeName"];
        $add["carmodelName"]=$car_out["carmodelName"];
        $add["inLaneCode"]=$car_out["inLaneCode"];
        $add["outLaneCode"]=$car_out["outLaneCode"];
        $add["id"]= Db::table("cxyun_query_order_log")->insertGetId($add);

        View::assign("duration",convertTime($add["stopTime"]*60));

        $add["inTime"]=substr($add["inTime"], 0, -4);
        View::assign("order_info",$add);
        $gateinfo=Db::table("cxyun_parking_gate")->where("gateId",$add["outLaneCode"])->find();
        View::assign("gateinfo",$gateinfo);
        return View::fetch();
    }
    
    
    public function createOrder(){
		//根据ID查询停车场信息
        $id=request()->post("id");
        $order_info=Db::table("cxyun_query_order_log")->where("id",$id)->find();
        if(empty($order_info)){
            return json(['info' => "查询账单失败"]);
        }
        $parkinginfo=Db::table("parkinglotinfo")->where("parkingNo",$order_info["parkingNo"])->find();
        if(empty($parkinginfo)){
            return json(['info' => "停车场信息错误"]);
        }
		
	
		//生成订单
		$data['appid'] = "wx3fd7e9c4152f4823";//公众账号ID
		$data['mch_id'] ="1484539292";//
		//根据停车场商户ID
		$data['sub_mch_id'] =$parkinginfo["mch_id"];
		$data['nonce_str'] = createNoncestr();//随机字符串
		$data['body'] = $parkinginfo["parkingName"]."-".$order_info["plateNumber"]."-".date('Y-m-d H:i:s');//商品描述
		$data['out_trade_no'] = date('YmdHis').rand(100000,999999);//商户订单号
		$data['total_fee'] = $order_info["upayFee"]*100;//总金额
		//$data['total_fee']=1;
		$data['spbill_create_ip'] = $_SERVER["REMOTE_ADDR"];//终端IP
		$data['notify_url'] = $this->getCurrentUrl().'/index/callback/wxnotice';//通知url
		$data['trade_type'] = 'JSAPI';
		$data['openid'] = session("wechat_openid");//用户标识

		$data['sign'] = MakeSign($data,env("APP.WECHAT_KEY"));//签名
		// return json(['info' => $data]);
		//输出xml字符
		
		$url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
		$payInfo = post_curl_data($url,ToXml($data));
		$payInfo = json_decode(json_encode(simplexml_load_string($payInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        Log::write($payInfo,"info");
		if($payInfo['return_code'] !== 'SUCCESS'){
			return json(['info' => $payInfo['return_msg']]);
		}if($payInfo['result_code'] !== 'SUCCESS'){
            return json(['info' => $payInfo['err_code_des']]);
        }else{
            unset($order_info["upayFee"]);
            unset($order_info["id"]);
            $info=$order_info;
            $info['query_order_log_id']=$id;
            $info['tradeNo'] =  $payInfo['prepay_id'];
            $info["subject"]=$data['body'];
            $info['outTradeNo'] =$data['out_trade_no'];
            $info["token"]=$data['sub_mch_id'];
            $info['createTime'] =  date("y-m-d H:i:s");
            $res=Db::table("cxyun_order")->insert($info);
			if($res){
			    $jsApiParameters['appId'] = $payInfo['appid'];
				//$jsApiParameters['timeStamp'] = time();
				$jsApiParameters['timeStamp'] = '$jsApiParameters["timeStamp"]';
				$jsApiParameters['nonceStr'] = createNoncestr();
				$jsApiParameters['package'] = 'prepay_id='.$payInfo['prepay_id'];
				$jsApiParameters['signType'] = 'MD5';
				$jsApiParameters['paySign'] = MakeSigns($jsApiParameters,env("APP.WECHAT_KEY"));
				return json(['jsApiParameters' => json_encode($jsApiParameters)]);
			}else{
				return json(['info' => '订单存储失败']);
			}
		}
	}
	

	//产生随机字符串，不长于32位



}